import * as hamcUtils from './gameUtils'

/**
 * 计算地雷位置
 * @param {number} mines - mine 数量 最大24个
 * @param {string} serverSeed - Server seed.
 * @param {string} clientSeed - Client seed.
 * @param {number} nonce - Nonce.
 * @returns {Array<number>} - 地雷位置结果.
 */
export function calculateMines(
	mines: number,
	serverSeed: string,
	clientSeed: string,
	nonce: number
) {
	mines = Math.min(mines, 24)
	const arrays = hamcUtils.getBytesGroups(serverSeed, clientSeed, nonce, mines, 4)
	const remainingPositions = Array(25)
		.fill(0)
		.map((_, index) => index)
	const result = []
	for (let i = 0; i < mines; i++) {
		const relativeMinePosition = Math.floor(hamcUtils.calculateResult(arrays[i], 25 - i))
		const [absoluteMinePosition] = remainingPositions.splice(relativeMinePosition, 1)
		result.push(absoluteMinePosition)
	}
	return result
}
/**
 * 地雷-赌场种子转换为字节-前端展示公开计算过程使用
 * @param {string} serverSeed - 服务端种子
 * @param {string} clientSeed - 客户端种子
 * @param {number} nonce - 随机数
 * @returns {object} - 返回字节对象
 */
export function casinoSeedToBytes(serverSeed: string, clientSeed: string, nonce: number) {
	return hamcUtils.casinoSeedToBytes(serverSeed, clientSeed, nonce, 3)
}
/**
 * 字节到数字的计算过程用到的分组 Mines 前端公开过程 24组，每组4个字节
 * @param {string} serverSeed - 服务端种子
 * @param {string} clientSeed - 客户端种子
 * @param {number} nonce - 随机数
 * @returns {array} - 返回字节数组
 */
export function bytesToNumberGroups(serverSeed: string, clientSeed: string, nonce: number) {
	return hamcUtils.getBytesGroups(serverSeed, clientSeed, nonce, 24, 4)
}

function factorial(n: number): any {
	return n < 2 ? 1 : n * factorial(n - 1)
}

function nCr(n: number, r: number) {
	return factorial(n) / (factorial(r) * factorial(n - r))
}

/**
 * 计算Mines倍率
 * @param {number} mines - 当前炸弹数量.
 * @param {number} diamonds - 已翻开的钻石数量.
 * @returns {number} - 返回赔率.
 */
export function calculateMultiplier(mines: number, diamonds: number) {
	const houseEdge = 0.01
	return ((1 - houseEdge) * nCr(25, diamonds)) / nCr(25 - mines, diamonds)
}
